package yannan.voiplock4ble.task;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

import yannan.voiplock4ble.utils.LogUtils;

/**
 * 作者：LiFukun
 * 日期：2017/3/13 13:16
 * 备注:查找通讯录中某电话号码的姓名
 */

public class SearchNickNameFromPhone extends Thread {
    private static Context mContxt;

    public static SearchNickNameFromPhone creat(Context context) {
        SearchNickNameFromPhone searchNickNameFromPhone = new SearchNickNameFromPhone();
        mContxt = context;
        return searchNickNameFromPhone;
    }

    @Override
    public void run() {
        getContactNameByPhoneNumber(mContxt, "177 1038 3913");
    }

    /*
       * 根据电话号码取得联系人姓名
       */
    public static String getContactNameByPhoneNumber(Context context, String phoneNumber) {
        String[] projection = {ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        // 将自己添加到 msPeers 中
        Cursor cursor = context.getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                projection, // Which columns to return.
                ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
                        + phoneNumber + "'", // WHERE clause.
                null, // WHERE clause value substitution
                null); // Sort order.

        if (cursor == null) {
            return null;
        }
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToPosition(i);

            // 取得联系人名字
            int nameFieldColumnIndex = cursor
                    .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
            String name = cursor.getString(nameFieldColumnIndex);
            LogUtils.i("姓名：" + name);
            return name;
        }
        return null;
    }
}
